import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'register',
    component: () => import('../views/Register')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login')
  },
  {
    path: '/index',
    name: 'index',
    component: () => import('../views/Index')
  },
  {
    path: '/realName',
    name: 'realName',
    component: () => import('../views/RealName')
  },
  {
    path: '/list/:type',
    name: 'list',
    component: () => import('../views/List')
  },
  {
    path: '/detail',
    name: 'detail',
    component: () => import('../views/Detail')
  },
  {
    path: '/userCenter',
    name: 'userCenter',
    component: () => import('../views/UserCenter')
  },
  {
    path: '/pay',
    name: 'pay',
    component: () => import('../views/Pay')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由变更之前，都会触发 beforeEach 指定的函数，确定变更必须调用next方法
// 在next之前进行一些判断处理，from: 来源路由规则对象，to: 目标路由规则对象
router.beforeEach((to, from, next) => {
  // 要求登录但是没有登录
  if ((to.path == "/detail" || to.path == "/userCenter") && sessionStorage.getItem("token") == null) {
    router.push('/login')
    return;
  }

  next();
})

export default router
